<script setup lang="js">
import { ref, onMounted } from 'vue'
import { genFileId } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
//cnpm install @ffmpeg/ffmpeg @ffmpeg/util
import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile, toBlobURL } from '@ffmpeg/util';
import { useConvert } from './a.ts'

// vue + ffmpeg.wasm demo
// https://github.com/ffmpegwasm/ffmpeg.wasm/blob/main/apps/vue-vite-app/src/components/FFmpegDemo.vue

//仅允许上传一个文件
const upload = ref([]) //上传的选择列表
function handleExceed(files) {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

//上传后的文件
const selectedFile = ref({})
async function handleChange(uploadFile, uploadFiles) {
  selectedFile.value = uploadFile
  console.log(uploadFile)
}

const { ffmpeg, transcode } = useConvert()
//触发转码操作
async function transcode() {
  const ffmpeg = new FFmpeg()
  await ffmpeg.load({
    coreURL: "/ffmpeg/ffmpeg-core.js",
    wasmURL: '/ffmpeg/ffmpeg-core.wasm',
    workerURL: `/ffmpeg/ffmpeg-core.worker.js`
  })

  await ffmpeg.writeFile('test.mkv', selectedFile.value?.raw)

  await ffmpeg.exec(['-i', 'test.mkv', 'test.mp4'])

  console.log("转码成功")
  const output = await ffmpeg.readFile('test.mp4')
  console.log(output)
  video = URL.createObjectURL(new Blob([(data).buffer], { type: 'video/mp4' }))
}

</script>

<template>
  <div class="common-layout">
    <el-container>
      <!-- header -->
      <el-header>你好</el-header>

      <el-container>
        <!-- left -->
        <el-aside width="30%">
          <el-upload class="upload-demo" ref="upload" drag :limit="1" :on-exceed="handleExceed" :on-change="handleChange">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              Drop file here or <em>click to upload</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                这里加一段描述, 比如可以转换什么样的文件
              </div>
            </template>
          </el-upload>
          <el-button type="primary" @click="transcode">转码</el-button>
        </el-aside>
        <!-- right -->
        <el-main>right</el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style></style>
